import type { AppTypeProps } from '@/types';

import { cloneDeep } from 'lodash-es';

import { nanoid } from 'nanoid';
import { acceptHMRUpdate, defineStore } from 'pinia';
import bus from 'vue3-eventbus';

import * as $config from '@/model/config';
import tool from '@/helper/tool';
import AppModel from '@/model/app';

interface AppState {
  showLogin: boolean;
  nowApp: AppTypeProps;
  openAppList: Array<AppTypeProps>;
  dockAppList: Array<AppTypeProps>;
  openWidgetList: Array<AppTypeProps>;
  launchpad: boolean;
  isDeskTop: boolean;
  windowState: 'fullscreen' | 'maximize' | 'minimize' | 'normal';
  elSize: '' | 'large' | 'small';
  setting: Record<string, any>;
}
function changeAlpha(rgbaColor: string, newAlpha: number): string {
  // 提取RGB部分和透明度部分
  const rgbaParts = rgbaColor.match(/\d+/g);
  if (!rgbaParts) {
    throw new Error('Invalid RGBA color format');
  }

  // 提取RGB值
  const [r, g, b] = rgbaParts.slice(0, 3);

  // 构建新的RGBA颜色值
  const newRgbaColor = `rgba(${r}, ${g}, ${b}, ${newAlpha})`;

  return newRgbaColor;
}

export const useAppStore = defineStore('wos-app', {
  actions: {
    /**
     * @description: 关闭应用
     */
    closeAllApp(app: AppTypeProps) {
      let idx1 = 0;
      for (const i in this.openAppList) {
        if (this.openAppList[i]?.key === app.key) {
          this.openAppList.splice(idx1, 1);
          break;
        }
        idx1++;
      }
      if (!app.keepInDock) {
        let idx2 = 0;
        for (const i in this.dockAppList) {
          if (this.dockAppList[i]?.key === app.key) {
            this.dockAppList.splice(idx2, 1);
            break;
          }
          idx2++;
        }
      }
      this.openTheLastApp();
    },
    /**
     * @description: 关闭应用
     */
    closeApp(app: AppTypeProps) {
      if (app.hideWhenClose) {
        this.hideApp(app);
      } else {
        let idx1 = 0;
        for (const i in this.openAppList) {
          if (app.pid) {
            if (this.openAppList[i]?.pid === app.pid) {
              this.openAppList.splice(idx1, 1);
              break;
            }
          } else {
            if (this.openAppList[i]?.key === app.key) {
              this.openAppList.splice(idx1, 1);
              break;
            }
          }
          idx1++;
        }
        if (!app.keepInDock) {
          let idx2 = 0;
          for (const i in this.dockAppList) {
            if (app.pid) {
              if (this.dockAppList[i]?.pid === app.pid) {
                this.dockAppList.splice(idx2, 1);
                break;
              }
            } else {
              if (this.dockAppList[i]?.key === app.key) {
                this.dockAppList.splice(idx2, 1);
                break;
              }
            }
            idx2++;
          }
        }
        this.openTheLastApp();
      }
    },
    /**
     * @description: 根据PID关闭应用
     */
    closeWithPid(pid: string) {
      let idx1 = 0;
      for (const i in this.openAppList) {
        if (this.openAppList[i]?.pid === pid) {
          this.openAppList.splice(idx1, 1);
          break;
        }
        idx1++;
      }
      let idx2 = 0;
      for (const i in this.dockAppList) {
        if (
          this.dockAppList[i]?.pid === pid &&
          !this.dockAppList[i]?.keepInDock
        ) {
          this.dockAppList.splice(idx2, 1);
          break;
        }
        idx2++;
      }
    },
    /**
     * @description: 获取常驻Dock的App列表
     */
    getDockAppList() {
      const arr = [];
      const appList = AppModel.allAppList as Array<AppTypeProps>;
      for (const app of appList) {
        if (app.keepInDock) {
          app.pid = nanoid(); // `${Date.now()}.${Number.parseInt(`${Math.random() * 99_999_999}`)}`;
          arr.push(app);
        }
      }
      this.dockAppList = arr as Array<AppTypeProps>;
    },
    /**
     * @description: 最小化应用
     */
    hideAllApp(app: AppTypeProps) {
      for (const i in this.openAppList) {
        if (this.openAppList[i] && this.openAppList[i]?.key === app.key) {
          this.openAppList[i].hide = true;
          break;
        }
      }
      this.openTheLastApp();
    },
    /**
     * @description: 最小化应用
     */
    hideApp(app: AppTypeProps) {
      for (const i in this.openAppList) {
        if (this.openAppList[i] && this.openAppList[i]?.pid === app.pid) {
          this.openAppList[i].hide = true;
          break;
        }
      }
      this.openTheLastApp();
    },
    loadDefaultFont() {
      const font = this.setting.font;
      const color = this.setting.color || 'default';
      const opacity = this.setting.opacity || 20;
      let _blod = `'PingFangSC-Semibold-ttf', sans-serif`;
      let _regular = `'PingFangSC-Regular-ttf', sans-serif`;
      switch (font) {
        case 'alipuhui': {
          _blod = `'AlibabaPuHuiTi-2-75-SemiBold', sans-serif`;
          _regular = `'AlibabaPuHuiTi-2-55-Regular', sans-serif`;
          break;
        }
        case 'hansans': {
          _blod = `'SourceHanSansCN-Regular', sans-serif`;
          _regular = `'SourceHanSansCN-Bold', sans-serif`;
          break;
        }
        case 'harmony': {
          _blod = `'HarmonyOS_Sans_SC_Blod', sans-serif`;
          _regular = `'HarmonyOS_Sans_SC_Regular', sans-serif`;
          break;
        }
        case 'pingfang': {
          _blod = `'PingFang-SC-Regular', sans-serif`;
          _regular = `'PingFang-SC-Semibold', sans-serif`;
          break;
        }
        default: {
          _blod = `'PingFangSC-Semibold-ttf', sans-serif`;
          _regular = `'PingFangSC-Regular-ttf', sans-serif`;
          break;
        }
      }
      $config.default.setting.color.find((item) => {
        if (item.name === color) {
          document.body.style.setProperty(
            '--wos-theme-frontbar-bg',
            changeAlpha(item.color, opacity / 100),
          );
          return item;
        }
        return null;
      });
      document.body.style.setProperty('--wos-font-family-bold', _blod);
      document.body.style.setProperty('--wos-font-family-regular', _regular);
    },
    /**
     * @description: 登录
     */
    login() {
      this.showLogin = false;
      this.isDeskTop = true;
    },
    /**
     * @description: 退出登录
     */
    logout() {
      this.nowApp = {} as AppTypeProps;
      this.openAppList = [];
      this.isDeskTop = false;
      this.showLogin = true;
    },
    /**
     * @description: 打开应用
     */
    openApp(app: AppTypeProps) {
      if (this.launchpad) {
        this.launchpad = false;
      }
      if (app.outLink) {
        app.url && window.open(app.url);
        return;
      }
      app.hide = false;
      let isExist = false;
      for (const i in this.openAppList) {
        if (this.openAppList[i]?.key === app.key) {
          isExist = true;
          break;
        }
      }

      if (isExist && !app.multiTask) {
        this.showApp(app);
      } else {
        app.pid = nanoid(); // `${Date.now()}.${Number.parseInt(`${Math.random() * 99_999_999}`)}`;
        app = cloneDeep(app);
        this.openAppList.push(app);
        let isExistDock = false;
        for (const i in this.dockAppList) {
          if (this.dockAppList[i]?.key === app.key) {
            // dock里已经有相同的应用了 不push
            isExistDock = true;
            break;
          }
        }
        if (!isExistDock) {
          this.dockAppList.push(app);
        }
      }
      this.nowApp = cloneDeep(app);
    },
    /**
     * @description: 根据key打开APP
     */
    openAppByKey(key: string) {
      const app = tool.getAppByKey(key);
      if (app) {
        this.openApp(app);
      }
    },
    openMenu(key: string) {
      switch (key) {
        case 'close': {
          this.closeApp(this.nowApp);
          break;
        }
        default: {
          bus.emit(key); // 默认通过事件总线发送，注意保证事件名称唯一
          break;
        }
      }
    },
    /**
     * @description: 打开上一次的应用
     */
    openTheLastApp() {
      for (let i = this.openAppList.length - 1; i >= 0; i--) {
        if (!this.openAppList[i]?.hide) {
          this.showApp(this.openAppList[i] as AppTypeProps);
          break;
        }
      }
      if (this.openAppList.length === 0) this.nowApp = {} as AppTypeProps;
    },
    /**
     * @description: 带参数打开App
     */
    openWithData(data: any) {
      data.app.data = data.data;
      this.openApp(data.app);
    },
    /**
     * 是否显示界面
     * @param show 是否显示
     */
    setIsDesktop(show: boolean) {
      this.isDeskTop = show;
    },
    setLaunchpad() {
      this.launchpad = !this.launchpad;
    },
    /**
     * 是否显示登录界面
     * @param show 是否显示
     */
    setShowLogin(show: boolean) {
      this.showLogin = show;
    },
    setWindowState(state: 'fullscreen' | 'maximize' | 'minimize' | 'normal') {
      this.windowState = state;
      this.elSize = state === 'normal' ? 'small' : '';
    },
    /**
     * @description: 显示并置顶APP
     */
    showApp(app: AppTypeProps) {
      const openAppList = cloneDeep(this.openAppList);
      let index = 0;
      for (const i in openAppList) {
        if (openAppList[i]?.pid === app.pid) {
          openAppList.splice(index, 1);
          break;
        }
        index++;
      }
      app.hide = false;
      app = cloneDeep(app);
      openAppList.push(app);
      this.openAppList = openAppList;
      this.nowApp = app;
    },
    updateSetting(updates: Record<string, any>) {
      Object.assign(this.setting, updates);
      this.loadDefaultFont();
    },
  },
  persist: true,
  state: (): AppState => ({
    dockAppList: [] as Array<AppTypeProps>,
    elSize: '',
    isDeskTop: false,
    launchpad: false,
    nowApp: {} as AppTypeProps,
    openAppList: [] as Array<AppTypeProps>,
    openWidgetList: [] as Array<AppTypeProps>,
    setting: {
      background: 'bg1',
      color: 'default',
      float: 'right',
      font: 'pingfang-sc',
      opacity: '20',
      theme: 'light',
    } as Record<string, any>,
    showLogin: true,
    windowState: 'normal',
  }),
});

// 解决热更新问题
const hot = import.meta.hot;
if (hot) {
  hot.accept(acceptHMRUpdate(useAppStore, hot));
}
